<?php

namespace app\admin\service;

use app\admin\dao\AccessDao;
use app\common\model\Access;
use app\common\model\Role;
use app\common\model\User;
use think\Collection;

/**
 * Class AccessService
 * @package app\admin\service
 */
class AccessService
{
    // dao
    private AccessDao $accessDao;

    public function __construct(AccessDao $accessDao)
    {
        $this->accessDao = $accessDao;
    }

    /**
     * @param User $user
     * @return Collection
     */
    public function index(User $user): Collection
    {

        // 超级管理员
        if ($user->isAdmin == 1) {

            return $this->accessDao->select()
                ->each(function (Access $access) {
                    $access->sub->each(function (Access $access) {
                        $access->isSel = '1';
                    });
                });
        }

        $roleId = $user->roleId;

        if (!is_id($roleId)) {
            return \think\model\Collection::make();
        }

        $role = Role::where('id', $roleId)
            ->with([
                'accesses',
            ])
            ->find();

        $accessIds = $role->accesses->column('id');

        return $this->accessDao->select()
            ->each(function (Access $access) use ($accessIds) {
                $access->sub->each(function (Access $access) use ($accessIds) {
                    if (in_array($access->id, $accessIds)) {
                        $access->isSel = '1';
                    } else {
                        $access->isSel = '0';
                        $access->path = '';
                    }
                });
            });
    }


}
